package com.itheima;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;

@WebServlet("/ServletNew")
public class ServletNew extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ArrayList<String> id = new ArrayList<>();
        String username = request.getParameter("username");
        String psw = request.getParameter("psw");
        String realPath = getServletContext().getRealPath("/user.txt");
        File file = new File(realPath);

        if (!file.exists()){
            BufferedWriter bw = new BufferedWriter(new FileWriter(realPath));
            bw.write(username+":"+psw);
            bw.newLine();
            bw.close();
        }else {
            BufferedReader br = new BufferedReader(new FileReader(realPath));
            String s;
            while ((s=br.readLine())!=null){
                String[] split = s.split(":");
                id.add(split[0]);
            }
            br.close();
            if (id.contains(username)){
                response.getWriter().write("注册用户名已存在,请重新注册.2s...");
                response.setHeader("Refresh","2;URL=newuser.jsp");
            }else{
                BufferedWriter bw = new BufferedWriter(new FileWriter(realPath,true));
                bw.write(username+":"+psw);
                bw.newLine();
                bw.close();
                response.sendRedirect(request.getContextPath()+"/login.jsp");
            }
        }


    }
}
